<?php
/**
 * HTTP API接口
 * 提供RESTful API用于Web管理界面
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 禁用缓存
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 数据存储文件
$dataFile = __DIR__ . '/data/devices.json';
$historyFile = __DIR__ . '/data/history.json';

// 确保数据目录存在并可写
$dataDir = __DIR__ . '/data';
if (!file_exists($dataDir)) {
    if (!mkdir($dataDir, 0777, true)) {
        error_log("ERROR: Failed to create data directory: $dataDir");
    } else {
        error_log("Created data directory: $dataDir");
        chmod($dataDir, 0777); // 确保可写
    }
} else {
    // 目录存在，检查是否可写
    if (!is_writable($dataDir)) {
        error_log("WARNING: Data directory is not writable: $dataDir");
        chmod($dataDir, 0777); // 尝试修改权限
    }
}

// 获取请求路径
$requestUri = $_SERVER['REQUEST_URI'];
$scriptName = dirname($_SERVER['SCRIPT_NAME']);
$path = str_replace($scriptName, '', parse_url($requestUri, PHP_URL_PATH));
$path = trim($path, '/');

// 调试日志
error_log("API Request - Method: {$_SERVER['REQUEST_METHOD']}, Path: $path");

// 路由处理
switch (true) {
    // 设备注册（新增）
    case $path === 'api/register' || $path === 'api.php/api/register':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleRegisterDevice();
        } else {
            response(['error' => 'Method not allowed'], 405);
        }
        break;
    
    // 位置上报（新增）
    case $path === 'api/location' || $path === 'api.php/api/location':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleReportLocation();
        } else {
            response(['error' => 'Method not allowed'], 405);
        }
        break;
    
    case $path === 'api/devices' || $path === 'api.php/api/devices':
        handleGetDevices();
        break;
        
    case preg_match('#^api\.php/api/device/([^/]+)/history$#', $path, $matches):
    case preg_match('#^api/device/([^/]+)/history$#', $path, $matches):
        handleGetDeviceHistory($matches[1]);
        break;
        
    case preg_match('#^api\.php/api/device/([^/]+)/request-location$#', $path, $matches):
    case preg_match('#^api/device/([^/]+)/request-location$#', $path, $matches):
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleRequestLocation($matches[1]);
        } else {
            response(['error' => 'Method not allowed'], 405);
        }
        break;
        
    case $path === '' || $path === 'index.php' || $path === 'api.php':
        // 返回管理界面
        include __DIR__ . '/index.html';
        exit;
        
    default:
        error_log("Route not found: $path");
        response([
            'error' => 'Not found',
            'path' => $path,
            'available_routes' => [
                'POST /api/register - Register device',
                'POST /api/location - Report location',
                'GET /api/devices - Get all devices',
                'GET /api/device/{id}/history - Get device history'
            ]
        ], 404);
}

// 设备注册处理（新增）
function handleRegisterDevice() {
    global $dataFile;
    
    // 获取POST数据
    $input = json_decode(file_get_contents('php://input'), true) ?: [];
    $deviceId = $input['device_id'] ?? 'unknown_' . time();
    $deviceName = $input['device_name'] ?? 'Unknown Device';
    
    error_log("Registering device: $deviceId - $deviceName");
    
    // 读取现有设备
    $devices = [];
    if (file_exists($dataFile)) {
        $data = file_get_contents($dataFile);
        $devices = json_decode($data, true) ?: [];
    }
    
    // 添加或更新设备
    $devices[$deviceId] = [
        'device_id' => $deviceId,
        'device_name' => $deviceName,
        'device_model' => $input['device_model'] ?? '',
        'android_version' => $input['android_version'] ?? '',
        'registered_at' => date('Y-m-d H:i:s'),
        'last_seen' => date('Y-m-d H:i:s'),
        'status' => 'online'
    ];
    
    // 保存
    file_put_contents($dataFile, json_encode($devices, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    
    error_log("Device registered successfully: $deviceId");
    
    response([
        'success' => true,
        'message' => 'Device registered successfully',
        'device_id' => $deviceId
    ]);
}

// 位置上报处理（新增）
function handleReportLocation() {
    global $dataFile, $historyFile;
    
    // 获取POST数据
    $input = json_decode(file_get_contents('php://input'), true) ?: [];
    $deviceId = $input['device_id'] ?? 'unknown';
    $latitude = $input['latitude'] ?? 0;
    $longitude = $input['longitude'] ?? 0;
    
    error_log("Received location from $deviceId: ($latitude, $longitude)");
    
    $locationData = [
        'latitude' => $latitude,
        'longitude' => $longitude,
        'accuracy' => $input['accuracy'] ?? 0,
        'timestamp' => $input['timestamp'] ?? date('Y-m-d H:i:s'),
        'address' => $input['address'] ?? '',
        'location_name' => $input['location_name'] ?? '',
        'is_simulated' => $input['is_simulated'] ?? false,
        'received_at' => date('Y-m-d H:i:s')
    ];
    
    // 读取历史记录
    $history = [];
    if (file_exists($historyFile)) {
        $data = file_get_contents($historyFile);
        $history = json_decode($data, true) ?: [];
    }
    
    // 添加新位置
    if (!isset($history[$deviceId])) {
        $history[$deviceId] = [];
    }
    
    $history[$deviceId][] = $locationData;
    
    // 只保留最近100条
    if (count($history[$deviceId]) > 100) {
        $history[$deviceId] = array_slice($history[$deviceId], -100);
    }
    
    // 保存历史记录
    $historyWriteResult = file_put_contents($historyFile, json_encode($history, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    if ($historyWriteResult === false) {
        error_log("ERROR: Failed to write to $historyFile - check directory permissions!");
    } else {
        error_log("History saved for $deviceId (wrote $historyWriteResult bytes)");
    }
    
    // 更新设备信息
    $devices = [];
    if (file_exists($dataFile)) {
        $data = file_get_contents($dataFile);
        $devices = json_decode($data, true) ?: [];
    }
    
    // 如果设备不存在，自动创建设备记录
    if (!isset($devices[$deviceId])) {
        error_log("Device $deviceId not found, creating new device record");
        $devices[$deviceId] = [
            'device_id' => $deviceId,
            'device_name' => 'Unknown Device',
            'device_model' => '',
            'android_version' => '',
            'registered_at' => date('Y-m-d H:i:s'),
            'last_seen' => date('Y-m-d H:i:s'),
            'status' => 'online',
            'last_location' => $locationData
        ];
    } else {
        // 设备存在，更新位置信息
        $devices[$deviceId]['last_seen'] = date('Y-m-d H:i:s');
        $devices[$deviceId]['last_location'] = $locationData;
        $devices[$deviceId]['status'] = 'online';
    }
    
    // 保存设备信息
    $writeResult = file_put_contents($dataFile, json_encode($devices, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    
    if ($writeResult === false) {
        error_log("ERROR: Failed to write to $dataFile - check directory permissions!");
    } else {
        error_log("Location saved successfully for $deviceId (wrote $writeResult bytes)");
    }
    
    response([
        'success' => true,
        'message' => 'Location received',
        'device_id' => $deviceId,
        'location' => $locationData
    ]);
}

function handleGetDevices() {
    global $dataFile;
    
    $devices = [];
    if (file_exists($dataFile)) {
        $data = file_get_contents($dataFile);
        $devices = json_decode($data, true) ?: [];
    }
    
    response(['devices' => array_values($devices)]);
}

function handleGetDeviceHistory($deviceId) {
    global $historyFile;
    
    $history = [];
    if (file_exists($historyFile)) {
        $data = file_get_contents($historyFile);
        $allHistory = json_decode($data, true) ?: [];
        $history = $allHistory[$deviceId] ?? [];
    }
    
    response([
        'device_id' => $deviceId,
        'history' => $history
    ]);
}

function handleRequestLocation($deviceId) {
    // 这个功能需要WebSocket服务器配合
    // 这里只是记录请求
    response([
        'success' => true,
        'message' => "已向设备 {$deviceId} 发送定位请求（需要WebSocket服务器运行）"
    ]);
}

function response($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}


